package com.unknow.first.dapp.admin.account.service.impl;

import com.unknow.first.dapp.admin.account.constants.ISystemAddressTypeEnum;
import com.unknow.first.dapp.admin.account.service.SystemAddressTypeService;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import lombok.SneakyThrows;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.stereotype.Service;

@Service
public class SystemAddressTypeServiceImpl implements SystemAddressTypeService {

    private final List<ISystemAddressTypeEnum> systemAddressTypeEnums = new ArrayList<>();

    @SneakyThrows
    @Lazy
    public SystemAddressTypeServiceImpl() {
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AssignableTypeFilter(ISystemAddressTypeEnum.class));
        Set<BeanDefinition> components = provider.findCandidateComponents("com.unknow.first.dapp.admin.account.constants");
        for (BeanDefinition component : components) {
            Class<? extends ISystemAddressTypeEnum> cls = (Class<? extends ISystemAddressTypeEnum>) Class.forName(component.getBeanClassName());
            ISystemAddressTypeEnum[] systemAddressTypes = cls.getEnumConstants();
            if (systemAddressTypes == null) {
                return;
            }
            for (ISystemAddressTypeEnum systemAddressTypeEnum : systemAddressTypes) {
                systemAddressTypeEnums.add(new ISystemAddressTypeEnum() {
                    @Override
                    public int getValue() {
                        return systemAddressTypeEnum.getValue();
                    }

                    @Override
                    public String getName() {
                        return systemAddressTypeEnum.getName();
                    }

                    @Override
                    public String getI18nValue() {
                        return systemAddressTypeEnum.getI18nValue();
                    }
                });
            }
            systemAddressTypeEnums.sort(Comparator.comparingInt(ISystemAddressTypeEnum::getValue));
        }

    }

    @Override
    public List<ISystemAddressTypeEnum> listSystemAddressType() {
        return systemAddressTypeEnums;
    }
}
